﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class Admin_Components_Permission_ChangePassword : System.Web.UI.UserControl
{

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            this.txtUserName.Text = Session["UserName"].ToString();
        }
    }
    protected void btnSave_Click(object sender, EventArgs e)
    {
        try
        {
            DBDataContext db = LINQUtil.GetDBWriteOnly();
            if (this.txtPassword.Text == "")
            {
                JavascriptUtil.LoadMessage(UpdatePanel1, false, "Vui lòng nhập password!");
                this.txtPassword.Focus();
                return;
            }
            if (this.txtConfirmPassword.Text != this.txtPassword.Text)
            {
                JavascriptUtil.LoadMessage(UpdatePanel1, false, "Password và Confirm Password phải giống nhau!");
                this.txtConfirmPassword.Focus();
                return;
            }

            string PasswordMD5 = Utils.Encrypt(this.txtPassword.Text);
            var us = db.Users.FirstOrDefault<User>(u => u.UserName == this.txtUserName.Text && u.Password == PasswordMD5);
            if (us != null)
            {
                JavascriptUtil.LoadMessage(UpdatePanel1, false, "Vui lòng nhập password khác với password cũ!");
                return;
            }

            var user = db.Users.FirstOrDefault<User>(u1 => u1.UserName == this.txtUserName.Text && (u1.Status == 'P' || u1.Status =='A'));
            if (user == null)
            {
                JavascriptUtil.LoadMessage(UpdatePanel1, false, "User không tồn tại");
                return;
            }
            user.Password = PasswordMD5;
            user.CreatedBy = Session["UserName"].ToString();
            user.LastUpdatedBy = Session["UserName"].ToString();
            user.CreatedDateTime = DateTime.Now;
            user.LastUpdatedDateTime = DateTime.Now;
            user.Status = 'A';
            db.Update<User>(user);
            db.SubmitChanges();
            Session["isChangePass"] = null;
            Session.Remove("isChangePass");

            JavascriptUtil.LoadMessage(UpdatePanel1, true, "Thành công !");
            this.btnSave.Enabled = false;
            Session["isChangePass"] = null;
            Response.Redirect("~/default.aspx",false);
        }
        catch (Exception ex)
        {
            this.btnSave.Enabled = true;
            JavascriptUtil.LoadMessage(UpdatePanel1, false, "Có lỗi xảy ra!");
            ControlUtil.LogError("-----------------------------");
            ControlUtil.LogError("ChangePassword-btnSave_Click");
            ControlUtil.LogError(ex.ToString());
            ControlUtil.LogError("-----------------------------");
        }
    }
}